<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="$t(title)" :v-if="dialogVisible" :visible.sync="dialogVisible" width="930px" top="10vh" @close='close'>
    <div class="dialogContentBoxMaxHeight80">
      <el-form ref="form" :model="record" label-width="70px" :rules="rules" class="blackForm" label-position="left" style="margin:0 20px;">
        <el-form-item :label="$t('策略名称')" prop="name">
          <el-input v-emoji v-model="record.name" size='small' v-if="title === '添加'" style="width:440px;" ref="recordName"></el-input>
          <span v-else>{{ record.showtitle }}</span>
        </el-form-item>
        <el-form-item :label="$t('描述')" prop="desc">
          <el-input v-emoji v-model="record.desc" v-if="title !== '模板详情'" ref="desc" :autosize="{ minRows: 4 }" size='small' style="width:440px;" type="textarea" @keydown.native="handleKeyCode($event)"></el-input>
          <span v-else>{{ record.desc }}</span>
        </el-form-item>
        <div class="strategyFatherBox" v-if="title !== '模板详情'">
          <el-button type="success" size='small' @click="largeConfig" class="addRule">{{$t('添加规则')}}</el-button>
        </div>
        <el-table ref="multipleTable" :data="record.services_map" size='mini' style="margin:10px 0 1px;" border>
          <el-table-column prop="rule_id" align='center' :label="$t('规则ID')" width="80" />
          <el-table-column prop="policyname" align='center' :label="$t('对象名')" min-width="100">
            <template slot-scope="scope">
              <tooltip :copyText="scope.row.policyname" class="wid190">
              </tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="action" align='center' :label="$t('动作')" min-width="80">
            <template slot-scope="scope">
              {{ $t('eventaction.' + actionList[scope.row.action]) }}
            </template>
          </el-table-column>
          <el-table-column prop="ipspolicyname" align='center' :label="$t('入侵防御策略名称')" min-width="120">
            <template slot-scope="scope">
              <tooltip :copyText="scope.row.ipspolicyname" class="wid190">
              </tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="avpolicyname" align='center' :label="$t('病毒过滤策略名称')" min-width="120">
            <template slot-scope="scope">
              <tooltip :copyText="scope.row.avpolicyname" class="wid190">
              </tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="urlpolicyname" align='center' :label="$t('URL策略名称')" min-width="120">
            <template slot-scope="scope">
              <tooltip :copyText="scope.row.urlpolicyname" class="wid190">
              </tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="conpolicyname" align='center' :label="$t('深度过滤策略名称')" min-width="120">
            <template slot-scope="scope">
              <tooltip :copyText="scope.row.conpolicyname" class="wid190">
              </tooltip>
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('操作')" fixed="right" width="100" v-if="title !== '模板详情'">
            <template slot-scope="scope">
              <el-button type="danger" plain @click="deleteRule(scope.row)" size='mini' :class="'del' + (scope.$index + 1)">{{$t('删除')}}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <rule-dialog v-if="ruleDialogVisible" ref="refRuleDialogVisible" @listData='listData'></rule-dialog>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" v-if="title !== '模板详情'" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { addTemplateInfo, editTemplateInfo, getTemplateInfo } from '@/api/safe/access/template'
import RuleDialog from './RuleDialog'
import { inputClass, texttextClass } from '@/utils/input-class.js'
export default {
  components: { RuleDialog },
  name: 'blackDialog',
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入策略名称')))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      ruleDialogVisible: false,
      title: '',
      record: {
        name: '',
        showtitle: '',
        desc: '',
        services_map: []
      },
      recordCopy: {
        name: '',
        showtitle: '',
        desc: '',
        services_map: []
      },
      deleteFlag: '',
      actionList: { 'ACCEPT': '允许', 'se': '安全引擎' },
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }]
      }
    }
  },
  watch: {
    'record.desc': {
      handler (newVal) {
        this.record.desc = newVal.replace(/[\r\n]/g, '')
      },
      immediate: true
    }
  },
  methods: {
    init (title, data) {
      this.dialogVisible = true
      this.title = title
      if (data) {
        this.deleteFlag = data.deleteFlag || ''
        getTemplateInfo({ name: data.title }).then(res => {
          this.record.name = res.info[0].title
          this.record.showtitle = res.info[0].showtitle
          this.record.desc = res.info[0].desc
          this.record.services_map = []
          for (let item of res.info[0].services) {
            let obj = {
              policyname: item.service_name,
              action: item.action
            }
            if (item.action === 'se') {
              obj['ipspolicyname'] = item.se_objects.ips
              obj['avpolicyname'] = item.se_objects.av
              obj['urlpolicyname'] = item.se_objects.url
              obj['conpolicyname'] = item.se_objects.dpi
            }
            this.record.services_map.push(obj)
          }
          this.ruleIdChange()
        })
      }
      this.$nextTick(() => {
        if (this.title === '添加') {
          const data = ['recordName']
          inputClass(this.$refs, data)
        }
        if (this.title !== '模板详情') {
          const textdata = ['desc']
          texttextClass(this.$refs, textdata)
        }
      })
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.record.services_map.length > 0) {
            var formData = Object.assign({}, this.record)
            formData.services_map = JSON.stringify(formData.services_map)
            if (this.title === '添加') {
              addTemplateInfo(formData).then(res => {
                if (res.status === 0) {
                  this.$messages.success(this.$t('添加成功'))
                  this.close()
                  this.$emit('templateAppData')
                }
              })
            } else {
              editTemplateInfo(formData).then(res => {
                if (res.status === 0) {
                  this.$messages.success(this.$t('编辑成功'))
                  this.close()
                  this.$emit('templateAppData')
                  this.$emit('nodeClick', { title: formData.name, desc: formData.desc, deleteFlag: this.deleteFlag })
                }
              })
            }
          } else {
            this.$messages.error(this.$t('请至少选择一条数据进行添加'))
          }
        }
      })
    },
    listData (data) {
      this.record.services_map.push(data)
      this.ruleIdChange()
    },
    // 重新分配规则id
    ruleIdChange () {
      this.record.services_map.forEach((tab, index) => {
        tab.rule_id = index + 1
      })
    },
    // 批量配置按钮
    largeConfig () {
      this.ruleDialogVisible = true
      this.$nextTick(() => {
        this.$refs.refRuleDialogVisible.init(this.record.services_map.length)
      })
    },
    close () {
      this.dialogVisible = false
      this.record = Object.assign({}, this.recordCopy)
      this.record.services_map = []
      this.title = ''
      this.$refs.multipleTable.clearSelection()
      this.$refs.form.resetFields()
    },
    deleteRule (row) {
      this.$confirm(this.$t('您是否要删除所选中的规则？'), this.$t('提示'), {
        closeOnClickModal: false,
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        confirmButtonClass: 'confirmButton',
        cancelButtonClass: 'confirmCancelButton',
        type: 'warning'
      }).then(() => {
        this.record.services_map.splice(row.rule_id - 1, 1)
        this.ruleIdChange()
      })
    },
    handleKeyCode (event) {
      if (event.keyCode === 13) {
        event.preventDefault() // 阻止浏览器默认换行操作
        return false
      }
    }
  }
}
</script>
